<template>
  <el-header>
    <!-- {{userInfo.password}} -->
    <el-row class="hrow">
      <el-col :span="8" class="hitem">
        <el-icon class="hicon" @click="setisCollapse(!isCollapse)">
          <ArrowLeftBold v-if="!isCollapse" />
          <ArrowRightBold v-else />
        </el-icon>
        <h2 class="title">社区疫情管理系统</h2>
      </el-col>
      <el-col :span="8" class="hitem">
        <!-- marquee使滚动内容的一种标签 -->
        <marquee behavior="" direction="">
          <div class="hlines">
            <h2>全民防疫,人人有责</h2>
            <h2>昨天做了核酸今天还要做</h2>
            <h2>出门戴口罩</h2>
          </div>
        </marquee>
      </el-col>
      <el-col :span="8" class="hitem">
        <div class="infos" v-if="userInfo">
          <el-dropdown @command="handleCommand">
            <!-- 选择下拉菜单 -->
            <span class="uname">
              {{ userInfo.username }}
              <el-icon class="el-icon--right">
                <arrow-down />
              </el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="home">首页</el-dropdown-item>
                <el-dropdown-item command="anno-list">公告</el-dropdown-item>
                <!-- 如果不写准确一些就找不到那一项了 -->
                <el-dropdown-item command="mine">个人信息</el-dropdown-item>
                <el-dropdown-item command="changepass" divided
                  >修改密码</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <!-- 这是一个展现当前用户身份权限的标签 -->
          <!-- bug来自于role不匹配，只有0到3的role，我给了一个7和4 -->
          <el-tag
            class="mar" 
            :color="roleList.find((item:any) => item.value == userInfo.role).color "
          >
            {{ roleList.find((item:any) => item.value == userInfo.role).label }}
          </el-tag>

          <el-tooltip
            class="box-item"
            effect="dark"
            content="切换头像"
            placement="bottom"
          >
            <MyAvatar :avatar="userInfo.avatar"></MyAvatar>
          </el-tooltip>
          <el-tooltip
            class="box-item"
            effect="dark"
            content="注销登录"
            placement="bottom"
          >
            <el-button
              class="mar"
              @click="todoLogOut"
              type="danger"
              :icon="SwitchButton"
              circle
            >
            </el-button>
          </el-tooltip>
        </div>
      </el-col>
      <el-dialog
        v-model="dialogVisible"
        title="修改密码"
        width="30%"
        :before-close="handleClose"
      >
        <el-form
          ref="formRef"
          :model="form"
          status-icon
          :rules="rules"
          label-width="120px"
          label-position="top"
          class="myform"
        >
          <el-form-item label="旧密码" prop="oldpass">
            <el-input
              :prefix-icon="Lock"
              clearable
              v-model="form.oldpass"
              placeholder="旧密码"
              show-password
              type="password"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="新密码" prop="newpass">
            <el-input
              :prefix-icon="Lock"
              clearable
              v-model="form.newpass"
              placeholder="新密码"
              show-password
              type="password"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="确认新密码" prop="dbnewpass">
            <el-input
              :prefix-icon="Lock"
              clearable
              v-model="form.dbnewpass"
              placeholder="确认新密码"
              show-password
              type="password"
              autocomplete="off"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="handleClose">取消</el-button>
            <el-button type="danger" @click="conformSetPass"
              >确认修改</el-button
            >
          </span>
        </template>
      </el-dialog>
    </el-row>
  </el-header>
</template>

<script setup lang="ts">
import { computed, ref, reactive } from "vue";
import { useStore } from "@/store";
import { useRouter } from "vue-router";
import { reg } from "@/utils/validate";
import { ShowErrorMsg } from "../../utils";
import { Ajax } from "@/api";
import MyAvatar from "./MyAvatar.vue";
import {  ElMessageBox } from 'element-plus'
import {
  ArrowLeftBold,
  ArrowRightBold,
  ArrowDown,
  SwitchButton,
  Lock,
} from "@element-plus/icons-vue";
const router = useRouter();
const store = useStore();
const formRef = ref<any>();
const form = reactive<any>({
  dbnewpass: "",
  oldpass: "",
  newpass: "",
});

defineProps({
  //不通过props传，通过pinia引入数据也可以
  userInfo: Object,
});
const dialogVisible = ref(false);
const roleList = computed(() => store.roleList);
const isCollapse = computed(() => store.isCollapse);
//引入侧边栏是否展示隐藏的布尔值
const { setisCollapse,setUserInfo } = store; //引入控制侧边栏展示隐藏/设置用户的方法

const handleCommand = (command: any) => {
  // command是command属性对应的值
  if (command == "changepass") {
    dialogVisible.value = true;
  } else {
    router.push({ name: command });
  }
};
const handleClose = () => {
  dialogVisible.value = false;
  formRef.value.resetFields();
};
const conformSetPass = () => {
  //修改密码
  formRef.value.validate(async (valid: boolean) => {
    console.log(valid);
    if (valid) {
      // 不用校验老密码与当前登录用户密码一致。因为后端方法中校验了
      let res: any = await Ajax.changepasst(form);
      if (res.code == 200) {
        //修改好以后移除token，移除pinia存的userInfo，重新登录
        sessionStorage.removeItem("yq_token");
        store.setUserInfo(null);
        router.replace("/login");
      }
    } else {
      ShowErrorMsg("密码校验失败");
    }
  });
};
const todoLogOut = ()=>{
  ElMessageBox.confirm(
    '你真的要注销登录吗？亲',
    '警告提示',
    {
      confirmButtonText:'确认',
      cancelButtonText:'取消',
      type:'warning'
    }
  ).then(()=>{
    sessionStorage.removeItem('yq_token')
    store.setUserInfo(null)
    router.replace("/login")//replace离开本页面不能点返回键回来
  })
}

const checkDbPass = (rule: any, value: any, callback: any) => {
  if (value !== form.newpass) {
    callback(new Error("两次密码不匹配!"));
  } else {
    callback();
  }
};
const checkpass = (rule: any, value: any, callback: any) => {
  if (reg.pwd.test(form.dbnewpass)) {
    formRef.value.validateField("dbnewpass", () => {
      callback();
    }); // 唤起 dbpass 的密码正则
  } else {
    callback();
  }
};

const rules = reactive<object>({
  oldpass: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
    {
      pattern: reg.pwd,
      message: "请输入6-16位的数字和字母组合的密码",
      trigger: "blur",
    },
  ],
  newpass: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
    {
      pattern: reg.pwd,
      message: "请输入6-16位的数字和字母组合的密码",
      trigger: "blur",
    },
    {
      validator: checkpass,
      trigger: "blur",
    },
  ],
  dbnewpass: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
    {
      pattern: reg.pwd,
      message: "请输入6-16位的数字和字母组合的密码",
      trigger: "blur",
    },
    {
      validator: checkDbPass,
      trigger: "blur",
    },
  ],
});
</script>

<style lang="scss" scoped>
.el-header {
  background: #123456;
  .hrow {
    height: 100%;
    .hitem {
      height: 100%;
      display: flex;
      align-items: center;
    }
    .hicon {
      font-size: 30px;
      color: #f50;
      cursor: pointer;
      margin-right: 6px;
    }
    .title {
      font-size: 20px;
      color: #f50;
    }
    .hlines {
      display: flex;
      color: #fff;
      h2 {
        margin: 0 15px;
      }
    }
    .infos {
      padding: 0 0 0 20px;
      display: flex;
      align-items: center;
      justify-content: space-evenly;
      width: 100%;
      .uname {
        color: #fff;
        font-size: 18px;
        display: flex;
        align-items: center;
        cursor: pointer;
      }
      .mar {
        margin: 0 10px;
        color: #fff;
      }
    }
  }
}
</style>
